namespace RuoVea.WeighIns.Server.Service;
using Microsoft.AspNetCore.Mvc;
using RuoVea.WeighIns.Server.Language;

/// <summary>
/// 时段字典服务
/// </summary>

[ApiExplorerSettings(GroupName = "RuoVea.WeighIns")]
public partial class MeridiemService : IApplicationService
{
    /// <summary>
    /// 数据仓储
    /// </summary>
    private readonly SugarRepository<InsMeridiem> _thisRepository;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="currentUser"></param>
    public MeridiemService(SugarRepository<InsMeridiem> thisRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns> 
    public async Task<RestfulResult<PageResult<InsMeridiem>>> GetPagesAsync(InstMeridiemPageParam? data)
    {
        var restful = new RestfulResult<PageResult<InsMeridiem>>() { Code = CodeStatus.OK };
        data ??= new InstMeridiemPageParam { PageNo = 1, PageSize = 10 };

        var query = await _thisRepository.AsQueryable()
            //.Where(u => u.Creator == _currentUser.UserId)
            .OrderBy(u => u.Sort) // 按排序字段排序
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 获取所有时段字典（简化列表）
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<InsMeridiem>>> GetlistAsync()
    {
        var restful = new RestfulResult<PageResult<InsMeridiem>>() { Code = CodeStatus.OK };
        PageParam data = new PageParam { PageNo = 1, PageSize = 100 };

        var query = await _thisRepository.AsQueryable()
            //.Where(u => u.IsDisable == YesOrNot.N)
            //.Where(u => u.Creator == _currentUser.UserId)
            .OrderBy(u => u.Sort) // 按排序字段升序排列
                                  //.OrderByDescending(u => u.IsDefault) // 默认项排前面
            .Select(u => new InsMeridiem
            {
                Id = u.Id,
                Code = u.Code,
                Name = u.Name,
                Sort = u.Sort
            })
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 增加时段字典
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task<RestfulResult> AddAsync(InsMeridiem data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        var isExist = await _thisRepository.IsAnyAsync(u =>
            (u.Name == data.Name || u.Code == data.Code) /*&& u.Creator == _currentUser.UserId*/);

        if (isExist)
        {
            restful.Message = i18n.data_duplicate;
            return restful;
        }

        //data.Creator = _currentUser.UserId;
        bool result = await _thisRepository.InsertAsync(data);

        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.add}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 更新时段字典
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> UpdateAsync(InsMeridiem data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        var isExist = await _thisRepository.IsAnyAsync(u =>
            u.Id == data.Id /*&& u.Creator == _currentUser.UserId*/);

        if (!isExist)
        {
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }

        bool result = await _thisRepository.UpdateAsync(data, true, true, $"{i18n.modify}");

        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.modify}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 删除时段字典
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns> 
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (data.Id == 0)
        {
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }

        bool isDelete = (await _thisRepository.FakeDeleteAsync(new InsMeridiem { Id = data.Id })) > 0;

        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.success}";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 根据代码获取时段字典
    /// </summary>
    /// <param name="code">时段代码</param>
    /// <returns></returns>
    public async Task<RestfulResult<InsMeridiem>> GetByCodeAsync(string code)
    {
        var restful = new RestfulResult<InsMeridiem>() { Code = CodeStatus.OK };

        var entity = await _thisRepository.AsQueryable()
            .Where(u => u.Code == code /*&& u.Creator == _currentUser.UserId && u.IsDisable == YesOrNot.N*/)
            .FirstAsync();

        if (entity == null)
        {
            restful.Code = CodeStatus.NotFound;
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }

        restful.Data = entity;
        return restful;
    }
}
